package com.u8.sdk;

import org.json.JSONObject;

import com.app.yjy.game.MiYuGame;
import com.miyu.game.lib.callback.MiYuGameCallback;
import com.miyu.game.lib.callback.MiYuGameExitCallback;
import com.miyu.game.lib.callback.MiYuGameLogoutListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Looper;
import android.util.Log;

public class MYSDK {

	enum SDKState {
		StateDefault, StateIniting, StateInited, StateLogin, StateLogined
	}

	private SDKState state = SDKState.StateDefault;
	private static MYSDK instance;
	private Activity GameActivity;
	private String appID;
	private String uid;
	private boolean islandScape;
	private static final String TAG = MYSDK.class.getSimpleName();

	private MYSDK() {

	}

	public static MYSDK getInstance() {
		if (instance == null) {
			instance = new MYSDK();
		}
		return instance;
	}

	private void parseSDKParams(SDKParams params) {
		this.appID = params.getString("AppID");
		Log.d(TAG, "获取appid = " + appID);
	}

	public void initSDK(Activity context, SDKParams params) {
		this.GameActivity = context;
		this.parseSDKParams(params);
		this.initSDK(context);
	}

	public void logout() {
		U8SDK.getInstance().onLogout();
		U8SDK.getInstance().onResult(U8Code.CODE_LOGOUT_SUCCESS, "logout");
		// Toast.makeText(GameActivity, "暂无此功能", Toast.LENGTH_LONG).show();
	}

	/**
	 * 必接功能<br>
	 * sdk初始化功能<br>
	 */
	public void initSDK(final Activity context) {
		Log.d(TAG, "==================SDK开始初始化==================");
		Log.d("是否调用主线程", (Thread.currentThread() == Looper.getMainLooper()
				.getThread()) + "");
		this.state = SDKState.StateIniting;
		Configuration mConfiguration = context.getResources()
				.getConfiguration();
		int ori = mConfiguration.orientation;
		// 判断横竖屏
		if (ori == Configuration.ORIENTATION_LANDSCAPE) {
			islandScape = true;
		} else if (ori == Configuration.ORIENTATION_PORTRAIT) {
			islandScape = false;
		}
		MiYuGame.splash(GameActivity, islandScape);
		U8SDK.getInstance().setActivityCallback(new IActivityCallback() {
			@Override
			public void onCreate() {
				MiYuGame.onCreate(GameActivity, new MiYuGameLogoutListener() {
					@Override
					public void onLogoutSuccess() {
						Log.d(TAG, "SDK注销成功");
						U8SDK.getInstance().onResult(
								U8Code.CODE_LOGOUT_SUCCESS,
								"sdk logout success");
						logout();
					}
				});
			}

			@Override
			public void onStop() {
				MiYuGame.onStop(GameActivity);
			}

			@Override
			public void onStart() {
				MiYuGame.onStart(GameActivity);
			}

			@Override
			public void onResume() {
				MiYuGame.onResume(GameActivity);
			}

			@Override
			public void onPause() {
				MiYuGame.onPause(GameActivity);
			}

			@Override
			public void onNewIntent(Intent newIntent) {
				MiYuGame.onNewIntent(newIntent, GameActivity);
			}

			@Override
			public void onDestroy() {
				MiYuGame.onDestroy(GameActivity);
			}

			@Override
			public void onActivityResult(int requestCode, int resultCode,
					Intent data) {
				MiYuGame.onActivityResult(GameActivity, requestCode,
						resultCode, data);
			}

			@Override
			public void onBackPressed() {
				MiYuGame.onBackPressed(GameActivity);
			}

			@Override
			public void onRestart() {
				// TODO Auto-generated method stub

			}
		});
		U8SDK.getInstance().onResult(U8Code.CODE_INIT_SUCCESS,
				"sdk init success");
	}

	private com.u8.sdk.LoginResult encodeLoginResult(String sid, String uid,
			String expand) {

		String sdkVersion = "1.0.0";
		String sp_id = "miyu";
		String appid = U8SDK.getInstance().getAppID();
		LoginResult loginResult = new LoginResult(sid, sp_id, uid, appid,
				sdkVersion, expand);
		Log.d(TAG, "登陆成功上传参数 = " + loginResult.toJsonString());
		return loginResult;
	}

	public void login(final Activity context) {
		Log.d(TAG, "==================SDK开始登录==================");
		Log.d("是否调用主线程", (Thread.currentThread() == Looper.getMainLooper()
				.getThread()) + "");
		if (!SDKTools.isNetworkAvailable(context)) {
			U8SDK.getInstance().onResult(U8Code.CODE_NO_NETWORK,
					"The network now is unavailable");
			return;
		}
		MiYuGame.login(GameActivity, new MiYuGameCallback() {
			@Override
			public void onMiYuGameSucess(String arg0) {

				try {
					JSONObject obj = new JSONObject(arg0);
					Log.d(TAG, "SDK登录回调的参数 = " + obj.toString());
					int result = obj.optInt("result");
					if (1 == result) {
						String sid = obj.optString("sessionid");
						uid = obj.optString("userid");
						U8SDK.getInstance().onResult(U8Code.CODE_LOGIN_SUCCESS,
								"sdk login success");
						U8SDK.getInstance().onLoginResult(
								encodeLoginResult(sid, uid, appID));
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}

			@Override
			public void onMiYuGameFailure() {
				U8SDK.getInstance().onResult(U8Code.CODE_LOGIN_FAIL,
						"sdk login fail");
			}

			@Override
			public void onMiYuGameCancel() {
				U8SDK.getInstance().onResult(U8Code.CODE_LOGIN_FAIL,
						"sdk login fail");
			}
		});
	}

	// 显示用户中心
	public void showAccountCenter() {

	}

	@SuppressLint("SimpleDateFormat")
	// 提交扩展数据
	public void submitExtendData(UserExtraData data) {
		Log.d(TAG, "==================SDK数据提交==================");
		// Log.d(TAG, "提交参数 = " + data.toJsonString());
		if (data.getDataType() == UserExtraData.TYPE_CREATE_ROLE) {
			Log.d(TAG, "创建角色数据提交");
			MiYuGame.createRole(GameActivity, uid, data.getServerID() + "",
					data.getServerName(), data.getRoleID() + "",
					data.getRoleName(), data.getRoleLevel() + "", "", "", "",
					"", "", "", MiYuGame.CREATEROLE,
					System.currentTimeMillis(), System.currentTimeMillis());
		} else if (data.getDataType() == UserExtraData.TYPE_ENTER_GAME) {
			Log.d(TAG, "进入游戏数据提交");
			MiYuGame.enterGame(GameActivity, uid, data.getServerID() + "",
					data.getServerName(), data.getRoleID() + "",
					data.getRoleName(), data.getRoleLevel() + "", "", "", "",
					"", "", "", MiYuGame.ENTERGAME, System.currentTimeMillis(),
					System.currentTimeMillis());
		} else if (data.getDataType() == UserExtraData.TYPE_LEVEL_UP) {
			Log.d(TAG, "角色升级数据提交");
			MiYuGame.levelChange(GameActivity, uid, data.getServerID() + "",
					data.getServerName(), data.getRoleID() + "",
					data.getRoleName(), data.getRoleLevel() + "", "", "", "",
					"", "", "", MiYuGame.LEVELCHANGE,
					System.currentTimeMillis(), System.currentTimeMillis());
		} else if (data.getDataType() == UserExtraData.TYPE_EXIT_GAME) {
			Log.d(TAG, "退出游戏数据提交");
			MiYuGame.exitGame(GameActivity, uid, data.getServerID() + "",
					data.getServerName(), data.getRoleID() + "",
					data.getRoleName(), data.getRoleLevel() + "", "", "", "",
					"", "", "", MiYuGame.EXITGAME, System.currentTimeMillis(),
					System.currentTimeMillis());
		} else if (data.getDataType() == UserExtraData.TYPE_SELECT_SERVER) {
			Log.d(TAG, "选择服务器数据提交");
			MiYuGame.selectServer(GameActivity, uid, data.getServerID() + "",
					data.getServerName(), data.getRoleID() + "",
					data.getRoleName(), MiYuGame.SELECTSERVER);
		}
	}

	public void pay(Activity context, com.u8.sdk.PayParams data) {
		Log.d(TAG, "==================SDK开始支付==================");
		Log.d("是否调用主线程", (Thread.currentThread() == Looper.getMainLooper()
				.getThread()) + "");
		try {
			// Log.d(TAG, "支付参数 = " + data.toJsonString());
			MiYuGame.pay(GameActivity, uid, data.getOrderKey(),
					data.getPrice() * 100, data.getProductId(),
					data.getProductDesc(), data.getProductName(),
					data.getExtension(), data.getVip(), data.getRoleLevel(),
					"no party", data.getRoleId(), data.getRoleName(),
					data.getServerId(), data.getServerName(),
					data.getOrderKey(), data.getProductName(),
					data.getServerName(), new MiYuGameCallback() {
						@Override
						public void onMiYuGameSucess(String arg0) {
							U8SDK.getInstance().onResult(
									U8Code.CODE_PAY_SUCCESS, "sdk pay success");
						}

						@Override
						public void onMiYuGameFailure() {
							U8SDK.getInstance().onResult(U8Code.CODE_PAY_FAIL,
									"sdk pay fail");
							Log.d(TAG, "SDK支付失败");
						}

						@Override
						public void onMiYuGameCancel() {
							U8SDK.getInstance().onResult(U8Code.CODE_PAY_FAIL,
									"sdk pay cancel");
							Log.d(TAG, "SDK支付取消");
						}
					});

		} catch (Exception e) {
			// e.printStackTrace();
		}
	}

	/**
	 * 必接功能<br>
	 * 当游戏退出前必须调用该方法，进行清理工作。建议在游戏退出事件中进行调用，必须在游戏退出前执行<br>
	 * 如果游戏直接退出，而不调用该方法，可能会出现未知错误，导致程序崩溃<br>
	 */
	public void sdkExit(final Activity context) {
		MiYuGame.exitGame(GameActivity, new MiYuGameExitCallback() {

			@Override
			public void exitGame() {
				GameActivity.finish();
				System.exit(0);
			}
		});
	}

	public boolean isInited() {

		return this.state.ordinal() >= SDKState.StateInited.ordinal();
	}

	public boolean isLogined() {

		return this.state.ordinal() >= SDKState.StateLogined.ordinal();
	}

}
